<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-sys__wsLog">
		
		<el-row :gutter="10">
		      <el-col :span="8">
		        <el-card style="height: calc(100vh - 125px)">
		          <div slot="header">
		            <span style="padding-right: 12px;"><i class="el-icon-collection" ></i> 策略列表</span>
					<el-link v-if="$hasPermission('redis:info')" icon="el-icon-warning-outline"  type="primary" @click="showInfo()"> 缓存信息</el-link>
		            <el-button
		              style="float: right; padding: 3px 0"
		              type="text"
		              icon="el-icon-refresh-right"
		              @click="getCacheMapList()"
		            ></el-button>
		          </div>
		          <el-table
		            v-loading="loading"
		            :data="cacheNames"
		            :height="tableHeight"
		            highlight-current-row
		            @row-click="getCacheMapChildList"
		            style="width: 100%"
		          >
		
		            <el-table-column
		              label="策略名称"
		              align="center"
		              prop="key"
		              :show-overflow-tooltip="true"
		            ></el-table-column>
		
		            <el-table-column
		              label="策略"
		              align="center"
		              prop="value"
		              :show-overflow-tooltip="true"
		            />
		          <!--  <el-table-column
		              label="操作"
		              width="60"
		              align="center"
		              class-name="small-padding fixed-width"
		            > -->
		             <!-- <template slot-scope="scope">
		                <el-button
		                  size="mini"
		                  type="text"
		                  icon="el-icon-delete"
		                  @click="handleClearCacheName(scope.row)"
		                ></el-button>
		              </template>
		            </el-table-column> -->
		          </el-table>
		        </el-card>
		      </el-col>
		
		
		
		      <el-col :span="8">
		        <el-card style="height: calc(100vh - 125px)">
		          <div slot="header">
		            <span><i class="el-icon-key"></i> 缓存列表</span>
		            <el-button
		              style="float: right; padding: 3px 0"
		              type="text"
		              icon="el-icon-refresh-right"
		              @click="getCacheMapChildList()"
		            ></el-button>
		          </div>
		          <el-table
		            v-loading="subLoading"
		            :data="cacheKeys"
		            :height="tableHeight"
		            highlight-current-row
		            @cell-click="getDetail"
		            style="width: 100%"
		          >
		            <el-table-column
		              label="序号"
		              width="60"
		              type="index"
		            ></el-table-column>
		            <el-table-column
		              label="缓存键名"
		              align="center"
		              :show-overflow-tooltip="true"
		              prop="key"
		            >
		            </el-table-column>
		            <el-table-column
		              label="操作"
		              width="60"
		              align="center"
		              class-name="small-padding fixed-width"
					  v-if="$hasPermission('redis:del')"
		            >
		              <template slot-scope="scope">
		                <el-button
		                  size="mini"
		                  type="text"
		                  icon="el-icon-delete"
		                  @click="delChildKey(scope.row)"
		                ></el-button>
		              </template>
		            </el-table-column>
		          </el-table>
		        </el-card>
		      </el-col>
		
		
		
		
		      <el-col :span="8">
		        <el-card :bordered="false" style="height: calc(100vh - 125px)" >
		          <div slot="header">
		            <span><i class="el-icon-document"></i>缓存内容</span>
					
					
					<el-tooltip placement="top" style="margin-left: 15px;">
						<div slot="content">
						   {{ this.typeRemark }}
						</div>
						<!-- elementui图标库：显示黑色的问号图标   -->
						<span><i class="el-icon-warning-outline"/> Type:{{ nowType }} TTL: {{ ttl }} Total: {{ nowItemTotal }}</span>
					</el-tooltip>
					
					
		            <el-button
		              style="float: right;padding-right: 15px; margin-top: -10px;"
		              type="text"
		              icon="el-icon-delete"
		              @click="delChildKey()"
					  v-if="$hasPermission('redis:del')"
		              ></el-button>
					  
					  <el-button
					    style="float: right; padding-right: 15px;margin-top: -10px;"
					    type="text"
					    icon="el-icon-circle-plus-outline"
						v-if="this.nowType !== 'string' && $hasPermission('redis:add')"
					    @click="showAddItem()"
					  ></el-button>
					  
					  <el-button
					    style="float: right; padding-right: 8px;margin-top: -10px;"
					    type="text"
					    icon="el-icon-refresh-right"
					    @click="getDetail()"
					  ></el-button>
		          </div>
		          <el-form :model="cacheForm" v-if="isString" v-loading="noStringLoading">
		            <el-row :gutter="32">
		              <el-col :offset="1" :span="22">
		                <el-form-item label="缓存策略:" prop="cacheName" >
		                  <el-input v-model="this.nowCacheName" :readOnly="true" :disabled="true"/>
		                </el-form-item>
		              </el-col>
		              <el-col :offset="1" :span="22">
		                <el-form-item label="缓存键名:" prop="cacheKey">
		                  <el-input @focus="copyName(cacheForm.key,true)" v-model="cacheForm.key" :readOnly="true" />
		                </el-form-item>
		              </el-col>
		              <el-col :offset="1" :span="22">
		                <el-form-item label="缓存内容:" prop="cacheValue">
		                  <el-input
		                    v-model="cacheForm.value"
		                    type="textarea"
		                    :rows="15"
		                  />
		                </el-form-item>
		              </el-col>
					  
					  <el-col :offset="1" :span="22">
						  <div style="display: flex;justify-content: center;">
							<el-button size="mini" type="primary" @click="getStrDetail()">{{ $t('detail') }}</el-button>
							
							<el-button size="mini" type="success" @click="showJson()">{{ $t('json') }}</el-button>
						  </div>
					  </el-col>
					  
		            </el-row>
		          </el-form>
				  
				  <!-- 这里内容的表格 -->
				  <div>
					  <span v-if="!isString">
						  <i class="el-icon-coin"></i> Key:
					  </span>
					  <el-link v-if="!isString" @click="copyName(nowCacheChildName,true)">{{ this.nowCacheChildName }}</el-link>
				  </div>
				  <el-table
				    v-loading="noStringLoading"
				    :data="noStringList"
				    :height="tableHeight"
				    highlight-current-row
				    style="width: 100%;margin-top: 10px;"
					:row-class-name="noStringClass"
					v-if="isString === false"
					@cell-click="delDetailItem"
				  >
					<el-table-column
					  label="序号"
					  width="60"
					  type="index"
					></el-table-column>
					
					<!-- zset -->
					<el-table-column
					  label="member"
					  align="center"
					  prop="element"
					  :show-overflow-tooltip="true"
					  v-if="nowType === 'zset'"
					></el-table-column>
					<el-table-column
					  label="score"
					  align="center"
					  prop="score"
					  :show-overflow-tooltip="true"
					  v-if="nowType === 'zset'"
					></el-table-column>
					
					<!-- set -->
					<el-table-column
					  label="member"
					  align="center"
					  prop="member"
					  :show-overflow-tooltip="true"
					  v-if="nowType === 'set'"
					></el-table-column>
					<!-- list -->
					<el-table-column
					  label="value"
					  align="center"
					  prop="value"
					  :show-overflow-tooltip="true"
					  v-if="nowType === 'list'"
					></el-table-column>
					
					
					<!-- hash -->
					<el-table-column
					  label="field"
					  align="center"
					  prop="field"
					  :show-overflow-tooltip="true"
					  v-if="nowType === 'hash'"
					></el-table-column>
					<el-table-column
					  label="value"
					  align="center"
					  prop="value"
					  :show-overflow-tooltip="true"
					  v-if="nowType === 'hash'"
					></el-table-column>
					
					
				   <el-table-column
				      label="操作"
				      width="60"
				      align="center"
				      class-name="small-padding fixed-width"
					  v-if="$hasPermission('redis:del')"
				    > 
				      <template slot-scope="scope">
				        <el-button
				          size="mini"
				          type="text"
				          icon="el-icon-delete"
				        ></el-button>
				      </template>
				    </el-table-column>
				  </el-table>
				  
		        </el-card>
		      </el-col>
		    </el-row>
		
		
		<detail :extendsParam="parentParam"  v-if="detailVisible" ref="detail" @refreshDataList="getDetail" @refreshStr="sxStr"></detail>
		<jsonDialog :extendsParam="jsonObj"  v-if="jsonVisible" ref="jsonDialog" ></jsonDialog>
		
		<el-dialog title="缓存信息" :visible.sync="infoVisible" width="70%">
			<table id="infoTable">
				<tr>
					<th>Redis版本</th>
					<th class="infoC">{{ cacheInfo.redis_version }}</th>
					
					<th>运行模式</th>
					<th class="infoC">{{ cacheInfo.redis_mode }}</th>
					
					<th>端 口</th>
					<th class="infoC">{{ cacheInfo.tcp_port }}</th>
					
					<th>客户端数</th>
					<th class="infoC">{{ cacheInfo.connected_clients }}</th>
				</tr>
				
				<tr>
					<th>运行时间</th>
					<th class="infoC">{{ cacheInfo.uptime_in_days }}天</th>
					
					<th>使用内存</th>
					<th class="infoC">{{ cacheInfo.used_memory_human }}</th>
					
					<th>内存峰值</th>
					<th  class="infoC">{{cacheInfo.used_memory_peak_human}}</th>
					
					<th>使用CPU</th>
					<th class="infoC">{{ cacheInfo.used_cpu_sys_children }}</th>
				</tr>
				
				<tr>
					<th>AOF是否开启</th>
					<th  class="infoC">{{ cacheInfo.aof_enabled === 0 ? '否' : '是'}}</th>
					
					<th>RDB是否成功</th>
					<th class="infoC">{{ cacheInfo.rdb_last_bgsave_status }}</th>
					
					<th>Key数量</th>
					<th class="infoC">{{ cacheInfo.dbSize }}</th>
					
					<th>网络入口/出口</th>
					<th class="infoC">{{ cacheInfo.instantaneous_input_kbps }}kps / {{cacheInfo.instantaneous_output_kbps}}kps</th>
					
				</tr>
			</table>
		  
		  <div slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="infoVisible = false">确 定</el-button>
		  </div>
		</el-dialog>
		
    </div>
  </el-card>
</template>

<script>
import { copyText } from '@/utils'
import Cookies from 'js-cookie'
import Detail from './redis-detail'
import JsonDialog from '../../../components/json_dialog'
export default {
  data () {
    return {
		cacheNames: [],
		cacheKeys: [],
		cacheForm: {},
		loading: true,
		subLoading: false,
		nowCacheName: "",
		nowCacheMapRemark: "",
		isString: true,
		tableHeight: window.innerHeight - 235,
		
		ttl: -1,
		nowType: "none",
		typeRemark: "暂无类型 TTL表示剩余时间,单位秒，其中-1为永久 -2不存在",
		noStringList: [],
		noStringLoading:false,
		nowCacheChildName: "",
		nowItemTotal: 0,
		
		detailVisible: false,
		parentParam: {},
		
		jsonVisible: false,
		jsonObj: {},
		
		infoVisible: false,
		cacheInfo: {}
	}
  },
  mounted() {
	  this.getCacheMapList();
  },
  components: {
	  Detail,
	  JsonDialog
  },
  methods:{
	  getCacheMapList(){
		  if( !this.$hasPermission('redis:cacheMapList') ){
			  this.$message.error('您没有权限查看策略列表哦~')
			  return;
		  }
		  
		  this.loading = true;
		  var p = {
			  params: {
				  keyContent: ''
			  }
		  }
		  this.$http.get('/pc/redis/cacheMapList',p).then(({ data: res }) => {
		    if (res.code !== 200) {
		      return this.$message.error(res.msg)
		    }
		  	this.cacheNames = res.data
			this.loading = false
			this.$message.success(res.msg)
		  }).catch(() => {})
	  },
	  getCacheMapChildList(row){
		  if( !this.$hasPermission('redis:cacheMapChildList') ){
			  this.$message.error('您没有权限查看缓存列表哦~')
			  return;
		  }
		  
		  this.subLoading = true;
		  const cacheName = row !== undefined ? row.key : this.nowCacheName;
		  const cacheMapRemark = row !== undefined ? row.value : this.nowCacheMapRemark;
			if (cacheName === "") {
				this.subLoading = false;
			  return;
			}
		  var p = {
			  params: {
				  key: cacheName
			  }
		  }
		this.$http.get('/pc/redis/cacheMapChildList',p).then(({ data: res }) => {
		  if (res.code !== 200) {
		    return this.$message.error(res.msg)
		  }
			this.cacheKeys = res.data;
			this.subLoading = false;
			this.nowCacheName = cacheName;
			this.nowCacheMapRemark =cacheMapRemark;
		}).catch(() => {})
	  },
	  getDetail(row,cl,x,event){
		  if( !this.$hasPermission('redis:get') ){
			  this.$message.error('您没有权限查看缓存详情哦~')
			  return;
		  }
		  
		  if( cl != undefined && cl.property !== 'key' ){
			  return;
		  }
		  if( row === undefined ){
			  row = {}
			  row.type = this.nowType;
			  row.key = this.nowCacheChildName;
		  }else{
			 this.nowCacheChildName =  row.key;
		  }
		  
		  this.noStringLoading = true;
		  
		  var p = { params: {key:row.key}}
		  this.$http.get('/pc/redis/get',p).then(({ data: res }) => {
		    if (res.code !== 200) {
		      this.$message.error(res.msg);
			  this.noStringLoading = false;
			  this.noStringList = [];
			  this.cacheForm = {};
			  return;
		    }
			this.isString = res.data.type === 'string'
		  	this.nowType = res.data.type;
			this.nowItemTotal = res.data.total;
			//设置类型的备注说明
			this.initTypeRemark(res.data.type);
			if( res.data.type === 'zset' ){
				this.noStringList =res.data.value;
			}else if( res.data.type === 'set' ){
				var tt = res.data.value;
				var setList = [];
				for (var i = 0; i < tt.length; i++) {
					setList.push( {member:tt[i]} )
				}
				this.noStringList = setList;
			}else if( res.data.type === 'string' ){
				this.cacheForm = res.data;
			}else if( res.data.type === 'hash' ){
				this.noStringList = res.data.value;
			}else if( res.data.type === 'list' ){
				var tt = res.data.value;
				var setList = [];
				for (var i = 0; i < tt.length; i++) {
					setList.push( {value:tt[i]} )
				}
				this.noStringList = setList;
			}else{
				return this.$message.error("存储类型不对哦~~~")
			}
			this.noStringLoading = false;
			this.nowCacheChildName = row.key;
			this.ttl = res.data.ttl;
		  }).catch(() => {})
	  },
	  delChildKey(row){
		  if( row === undefined && this.nowCacheChildName != '' ){
			  row = {}
			  row.key = this.nowCacheChildName;
		  }else if( row === undefined && this.nowCacheChildName === '' ){
			  this.$message.error( '不存在的key' );
			  return;
		  }
		   this.$confirm('此操作将永久删除该缓存, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'error'
		  }).then(() => {
			//删除key
			var p = {
			  key: row.key
			}
			this.$http.post('/pc/redis/del',p).then(({ data: res }) => {
			  if (res.code !== 200) {
				return   this.$message.error(res.msg);
			  }
			  if( res.data > 0 )  {
				//删除成功，刷新当前列表
				this.getCacheMapChildList();  
				//如果当前的key和详情的key一致则清空详情内容
				if( this.nowCacheChildName === row.key ){
					//清空表单
					this.noStringList = [];
					this.nowCacheChildName = "";
					this.cacheForm = {}
				}
			  }else{
				  this.getCacheMapChildList();  
				  if( this.nowCacheChildName === row.key ){
				  	//清空表单
				  	this.noStringList = [];
				  	this.nowCacheChildName = "";
					this.cacheForm = {}
				  }
				  this.$message.error("缓存不存在或删除失败");
			  }
			}).catch(() => {
				
			});
		  }).catch(() => {
			this.$message({
			  type: 'info',
			  message: '已取消删除'
			});          
		  });
	  }
	  ,
	  getStrDetail(){
		  var pp = {}
		  pp.key = this.nowCacheChildName;
		  pp.type = this.nowType;
		  pp.ttl = this.ttl;
		  pp.value = this.cacheForm.value;
		  pp.isAdd = false; //true-新增 false-编辑
		  pp.cacheMapKey = this.nowCacheName;
		  pp.cacheMapRemark = this.nowCacheMapRemark;
		  this.parentParam = pp
		  this.detailVisible = true
		  this.$nextTick(() => {
		    this.$refs.detail.init()
		  })
		  return;
	  },
	  delDetailItem(row,cl,x,event){
		  var clLabel = cl.label;
		  if( clLabel !== '操作' ){
			  // alert(cl.label + "弹出详情")
			  var pp = {}
			  pp.key = this.nowCacheChildName;
			  pp.type = this.nowType;
			  pp.ttl = this.ttl;
			  pp.index = row.index;
			  pp.value = row.value;
			  pp.field = row.field;
			  pp.member = row.member;
			  pp.score = row.score;
			  pp.element = row.element;
			  pp.isAdd = false; //true-新增 false-编辑
			  pp.cacheMapKey = this.nowCacheName;
			  pp.cacheMapRemark = this.nowCacheMapRemark
			  this.parentParam = pp
			  this.detailVisible = true
			  this.$nextTick(() => {
			    this.$refs.detail.init()
			  })
			  return;
		  }
		  
			this.$confirm('此操作将永久删除该缓存子项, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'error'
			}).then(() => {
				var p = {
					key: this.nowCacheChildName,
					type: this.nowType,
					index: row.index
				}
				if( this.nowType === 'hash' ){
					p.value = row.field;
				}else if( this.nowType === 'set' ){
					p.value = row.member
				}else if( this.nowType === 'zset'){
					p.value = row.element
				}else if( this.nowType === 'list'){
					p.value = row.value
				}
				
				this.$http.post('/pc/redis/del',p).then(({ data: res }) => {
					if (res.code !== 200) {
						return this.$message.error(res.msg);
					}
					if( res.data > 0 )  {
						this.getDetail();
					}else{
						return this.$message.error("该缓存不存在或删除失败~");
					}
				}).catch(() => {});
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});          
			});
		}
		,noStringClass({ row, rowIndex }) {
			row.index = rowIndex;
		}
		,showAddItem(){
			if( !this.nowCacheChildName ){
				return this.$message.error("请选择缓存键名~");
			}
			var pp = {}
			pp.key = this.nowCacheChildName;
			pp.type = this.nowType;
			pp.ttl = this.ttl;
			pp.value = "";
			pp.field = "";
			pp.member = "";
			pp.score = 0;
			pp.element = "";
			pp.isAdd = true; //true-新增 false-编辑
			pp.isLeft = true;
			pp.cacheMapKey = this.nowCacheName;
			pp.cacheMapRemark = this.nowCacheMapRemark;
			this.parentParam = pp
			this.detailVisible = true
			this.$nextTick(() => {
			  this.$refs.detail.init()
			})
			return;
		}
		,sxStr(){
			//详情李如果刷新了字符串类型的，则刷新父级，清空表单
			this.nowType = 'none'
			this.noStringList = [];
			this.nowCacheChildName = "";
			this.cacheForm = {}
			this.ttl = -1
			this.getCacheMapChildList();  
		}
		,copyName( t,i ){
			copyText(t,i);
		}
		,initTypeRemark(shuo){
			if( shuo === 'none' ){
				this.typeRemark = '类型错误~'
			}else if( shuo === 'string' ){
				this.typeRemark = "1、不提供新增功能  2、key非空唯一"
			}else if( shuo === 'list' ){
				this.typeRemark = "可重复可新增修改"
			}else if( shuo === 'set' ){
				this.typeRemark = "1、修改请先增后删  2、不可重复"
			}else if( shuo === 'zset' ){
					this.typeRemark = "1、不可重复,重复则为修改  2、修改请先增后删  "
			}else if( shuo === 'hash' ){
					this.typeRemark = "1、Field不可重复,重复视为修改  2、改Field请先增后删"
			}else{
				this.typeRemark = '暂不支持该类型 ' + shuo;	
			}
		}
		,showJson(){
			//深拷贝
			var ttt = JSON.parse(JSON.stringify(this.cacheForm))
			this.jsonObj = ttt;
			this.jsonVisible = true;
			this.$nextTick(() => {
			  this.$refs.jsonDialog.init()
			})
		}
		,showInfo(){
			this.$http.get('/pc/redis/info').then(({ data: res }) => {
				if (res.code !== 200) {
					return this.$message.error(res.msg);
				}
				this.cacheInfo = res.data;
				this.infoVisible = true;;
			}).catch(() => {});
		}
  }
  ,
  destroyed () {
	  
  }
}
</script>

<style>
	
	#infoTable {
		border-collapse: collapse;
		width: 100%;
		text-align:left;
	}
	
	#infoTable  tr{
		border-bottom: 1px solid #dfe6ec;
		height: 70px;
	}
	
	 #infoTable:not(.info) {
		color:#92979a;
	}
	
	.infoC {
		color:#409EFF;
	}
	
</style>

